package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.identity.UpdateProjectCmd;
import cn.easyplatform.studio.context.Contexts;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.web.editors.EditorCallback;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zul.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PropertiesView extends AbstractView<String> {
    private Vlayout vlayout;
    private Listbox sourcesBox;

    /**
     * @param cb
     */
    protected PropertiesView(EditorCallback<String> cb) {
        super(cb);
    }

    @Override
    protected void createContent(Component parent) {

        vlayout = new Vlayout();
        vlayout.setVflex("1");

        Hlayout topHlayout = new Hlayout();
        topHlayout.setHflex("1");
        Button btnTop = new Button(Labels.getLabel("button.create") + Labels.getLabel("button.property"));
        btnTop.setSclass("pull-right");
        btnTop.setIconSclass("z-icon-plus");
        btnTop.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                List<Listitem> items = sourcesBox.getItems();
                Listitem ti = new Listitem();
                Listcell listcell1 = new Listcell();
                Combobox textbox1 = new Combobox();
                textbox1.appendItem("config");
                textbox1.appendItem("dateFormat");
                textbox1.appendItem("dao.authenticationQuery");
                //textbox1.appendItem("app.webContainer.path");
                textbox1.appendItem("businessDateHandlerFactory");
                textbox1.appendItem("dao.userAgentQuery");
                textbox1.appendItem("bpmEngineContextFactory");
                textbox1.appendItem("dao.authenticationQuery");
                textbox1.appendItem("dao.accQuery");
                textbox1.appendItem("dao.orgSubQuery");
                textbox1.appendItem("dao.userAgentRoleQuery");
                textbox1.setStyle("margin:3px");
                listcell1.appendChild(textbox1);
                Listcell listcell2 = new Listcell();
                final Textbox textbox2 = new Textbox();
                textbox2.setHflex("1");
                textbox2.setStyle("margin:3px");
                textbox2.setRows(2);
                listcell2.appendChild(textbox2);
                textbox1.addEventListener(Events.ON_CHANGE, new EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        System.out.println(event);
                        InputEvent inputEvent = (InputEvent) event;
                        if (inputEvent.getValue().equals("app.webContainer.path")){
                            textbox2.setPlaceholder(Labels.getLabel("editor.appPath.placeholder"));
                        }else {
                            textbox2.setPlaceholder("");
                        }
                    }
                });
                ti.appendChild(listcell1);
                ti.appendChild(listcell2);
                items.add(ti);
            }
        });
        btnTop.setParent(topHlayout);
        topHlayout.setParent(vlayout);

        Button btnTopRe = new Button(Labels.getLabel("button.remove") + Labels.getLabel("button.property"));
        btnTopRe.setSclass("pull-right");
        btnTopRe.setIconSclass("z-icon-minus");
        btnTopRe.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
                if (sourcesBox.getSelectedItem() == null) {
                    WebUtils.showError(Labels.getLabel("editor.select", new String[]{Labels.getLabel("entity.list")}));
                    return;
                }
                Listitem listitem = sourcesBox.getSelectedItem();
                sourcesBox.getItems().remove(listitem);
            }
        });
        btnTopRe.setParent(topHlayout);
        topHlayout.setParent(vlayout);

        Hlayout centerHlayout = new Hlayout();
        centerHlayout.setHflex("1");
        centerHlayout.setVflex("1");
        centerHlayout.setStyle("padding-top:3px");

        sourcesBox = new Listbox();
        sourcesBox.setHflex("1");
        sourcesBox.setVflex("1");
        sourcesBox.setCheckmark(true);
        sourcesBox.setMold("paging");
        sourcesBox.setPageSize(20);
        sourcesBox.setParent(centerHlayout);

        Listhead listhead = new Listhead();
        listhead.setSizable(true);
        listhead.setParent(sourcesBox);

        Listheader idListheader = new Listheader();
        idListheader.setLabel("key");
        idListheader.setHflex("2");
        idListheader.setParent(listhead);

        Listheader nameListheader = new Listheader();
        nameListheader.setLabel("value");
        nameListheader.setHflex("3");
        nameListheader.setParent(listhead);

        centerHlayout.setParent(vlayout);
        vlayout.setParent(parent);

        Hlayout bottomHlayout = new Hlayout();
        bottomHlayout.setHflex("1");

        Hlayout h = new Hlayout();
        h.setHflex("1");
        h.setParent(bottomHlayout);
        Button btn = new Button(Labels.getLabel("button.save"));
        btn.setId("saveBtn");
        btn.setSclass("pull-right");
        btn.setIconSclass("z-icon-check");
        btn.addEventListener(Events.ON_CLICK, this);
        btn.setParent(bottomHlayout);

        Button close = new Button(Labels.getLabel("editor.file.close"));
        close.setId("closeBtn");
        close.setSclass("pull-right");
        close.setIconSclass("z-icon-close");
        close.addEventListener(Events.ON_CLICK, this);
        close.setParent(bottomHlayout);

        bottomHlayout.setParent(vlayout);
        redraw();
    }

    private void redraw() {
        createTables(Contexts.getProject().getProperties());
    }

    private void createTables(Map<String, String> map) {
        List<Listitem> items = sourcesBox.getItems();
        for (String key : map.keySet()) {
            if (key.startsWith("tools.") == false) {
                Listitem ti = new Listitem();
                Listcell listcell1 = new Listcell(key);
                Listcell listcell2 = new Listcell();
                Textbox textbox2 = new Textbox();
                textbox2.setHflex("1");
                textbox2.setStyle("margin:3px");
                textbox2.setValue(map.get(key));
                textbox2.setInplace(true);
                if (map.get(key).length() > 64)
                    textbox2.setRows(4);
                listcell2.appendChild(textbox2);
                ti.appendChild(listcell1);
                ti.appendChild(listcell2);
                //ti.addEventListener(Events.ON_DOUBLE_CLICK, this);
                items.add(ti);
            }
        }
    }

    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().getId().equals("saveBtn"))
            save();
        if (event.getTarget().getId().equals("closeBtn"))
            vlayout.getRoot().detach();
    }

    private void save() {
        for (Listitem listitem : sourcesBox.getItems()) {
            String keyStr = "";
            if (listitem.getFirstChild().getFirstChild() == null) {
                keyStr = ((Listcell) listitem.getFirstChild()).getLabel();
            } else {
                keyStr = ((Combobox) listitem.getFirstChild().getFirstChild()).getValue();
            }
            String valueStr = ((Textbox) listitem.getLastChild().getLastChild()).getValue();
            if (Strings.isBlank(keyStr)) {
                WebUtils.showError(Labels.getLabel("message.no.empty", new String[]{"key"}));
                return;
            }
            if (Strings.isBlank(valueStr)) {
                WebUtils.showError(Labels.getLabel("message.no.empty", new String[]{"value"}));
                return;
            }
        }
        Map<String, String> proMap = Contexts.getProject().getProperties();
        List<String> deleteKey = new ArrayList<>();
        for (String key:
                Contexts.getProject().getProperties().keySet()) {
            if (key.startsWith("tools.") == false) {
                deleteKey.add(key);
            }
        }

        for (String key :
                deleteKey) {
            proMap.remove(key);
        }
        for (Listitem listitem : sourcesBox.getItems()) {
            String keyStr = "";
            if (listitem.getFirstChild().getFirstChild() == null) {
                keyStr = ((Listcell) listitem.getFirstChild()).getLabel();
            } else {
                keyStr = ((Combobox) listitem.getFirstChild().getFirstChild()).getValue();
            }
            String valueStr = ((Textbox) listitem.getLastChild().getLastChild()).getValue();
            proMap.put(keyStr, valueStr);
        }
        Contexts.getProject().setProperties(proMap);
        StudioApp.execute(new UpdateProjectCmd());
        vlayout.getRoot().detach();
    }

}
